import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { getModulesApi } from "@/api/jsonData.js";

const storeSetup = () => {
  /* 定义数据--------------------------------------------------------------------- */

  // 所有类别数据
  const allCategoryData = ref([]);

  // 类别列表
  const categorys = ref([]);

  // 当前选择的类别
  const currentCategory = ref(1);

  // 显示模块列表
  const showModules = ref([]);

  // 模块滚动方向标识
  const currentScrollDirection = ref("bottom");

  // 切换分类次数统计
  const checkCategoryCount = ref(0);

  // 是否显示模块盒子的标识
  const isShowModuleBox = ref(true);

  /* 定义函数--------------------------------------------------------------------- */
  // 查询所有模块数据
  const getModulesFunc = async () => {
    await getModulesApi().then((res) => {
      // 收集所有数据
      allCategoryData.value = res.data;

      // 整理类别数据
      categorys.value = res.data.map((category) => {
        if (category.categoryId == currentCategory.value) {
          showModules.value = category.modules;
        }

        return {
          categoryId: category.categoryId,
          categoryIcon: category.categoryIcon,
          categoryName: category.categoryName,
          categoryTitle: category.categoryTitle,
        };
      });

      console.log(categorys);
    });
  };

  // 设置选种的类别
  const setSelectedCategory = (categoryId) => {
    if (categoryId > currentCategory.value) {
      currentScrollDirection.value = "top";
    } else {
      currentScrollDirection.value = "bottom";
    }
    currentScrollDirection.value;
    currentCategory.value = categoryId;
    setModules();
  };

  // 设置模块数据
  const setModules = () => {
    checkCategoryCount.value += 1;
    allCategoryData.value.forEach((category) => {
      if (category.categoryId == currentCategory.value) {
        showModules.value = category.modules;
      }
    });
    reloadModuleBox();
  };

  // 刷新模块盒子
  const reloadModuleBox = () => {
    isShowModuleBox.value = false;
    setTimeout(() => {
      isShowModuleBox.value = true;
    }, 100);
  };

  // 返回参数
  return {
    showModules,
    currentCategory,
    categorys,
    currentScrollDirection,
    checkCategoryCount,
    isShowModuleBox,
    getModulesFunc,
    setModules,
    setSelectedCategory,
  };
};

// 导出Store
export const useContentStore = defineStore("content", storeSetup, {
  persist: false,
});
